package myArrayList;

import java.util.Arrays;

//假设数组元素都是int型
public class MyArrayList {
    public static final int DEFUALT_SIZE = 3;//默认大小
    int[] arr;
    int curSize = 0; //当前容量

    public MyArrayList() {
        this.arr = new int[DEFUALT_SIZE];
    }
    //判断是否满了
    public boolean isFull() {
        return this.curSize >= arr.length;
    }
    //判断是否是空的
    public boolean isEmpty() {
        return this.curSize == 0;
    }
    //获取数组有效空间
    public int size() {
        return this.curSize;
    }
    //判断更改位置有没有前驱
    private boolean isVaild(int index) {
        return index > this.curSize;
    }
    //数组扩容
    public void grow() {
        this.arr = Arrays.copyOf(arr, 2 * arr.length);
    }
    //add方法
    public void add(int val) {
        if (isFull()) {
            grow(); //满了就扩容
        }
        this.arr[curSize++] = val;
    }
    //向指定下标更新值add方法
    public void add(int index, int val) {
        if (isVaild(index)) {  //如果目标索引没有前驱，那就抛出异常
            throw new MyArrayListException("目标索引没有前驱");
        }
        if (isFull()) {
            grow();
        }
        for (int i = curSize - 1; i >= index; i--) {
            arr[i + 1] = arr[i];
        }
        arr[index] = val;
        curSize++;
    }
    public void display() {
        System.out.print("[");
        for (int i = 0; i < curSize; i++) {
            System.out.print(arr[i]);
            if (i != curSize - 1) {
                System.out.print(",");
            }
        }
        System.out.print("]");
    }
    public int get(int index) {
        if (isVaild(index)) {
            throw new MyArrayListException("目标索引没有前驱");
        }
        return arr[index];
    }
    public void set(int index, int val) {
        if (isVaild(index) || index < 0) {
            throw new MyArrayListException("目标索引没有前驱");
        }
        arr[index] = val;
    }
    public void clear() {
        curSize = 0;
    }
    public int contains(int tofind) {
        for (int i = 0; i < curSize; i++) {
            if (arr[i] == tofind) {
                return i;
            }
        }
        return -1;
    }
}
